package com.zr.utils;

import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Map;

public class PageUtil<T> {
    /**
     * 总记录数
     */
    private int totalRow;
    /**
     * 当前页码
     */

    private int pageNo;
    /**
     * 每页记录数
     */
    private int pageSize = 10;
    /**
     * 起始记录下标
     */

    private int beginIndex;
    /**
     * 总页数
     */

    private int totalPage;
    /**
     * 截止记录下标
     */

    private int endIndex;
    /**
     *
     */
    private List<T> resultList;

    public PageUtil(int totalRow, int pageNo) {
        this.totalRow = totalRow;
        this.pageNo = pageNo;
        calculate();
    }

    public PageUtil(int totalRow, Map formData) {
        String pageCopy = (String) formData.get("pageCopy");
        if (!StringUtils.isEmpty(pageCopy)) {
            Integer page = Integer.valueOf(pageCopy);
            if (page != null) {
                page++;
            }
            Integer rows = (Integer) formData.get("rows");
            if (page != null && rows != null) {
                this.totalRow = totalRow;
                this.pageNo = page;
                this.pageSize = rows;
            }
            calculate();
        }

    }

    public PageUtil(int totalRow, int pageNo, int pageSize) {
        this.totalRow = totalRow;
        if (pageNo > 0) {
            this.pageNo = pageNo;
        }
        if (pageSize > 0) {
            this.pageSize = pageSize;
        }
        calculate();
    }

    private void calculate() {
        totalPage = totalRow / pageSize + ((totalRow % pageSize) > 0 ? 1 : 0);

        if (pageNo > totalPage) {
            pageNo = totalPage;
        } else if (pageNo < 1) {
            pageNo = 1;
        }

        beginIndex = (pageNo - 1) * pageSize;
        if (beginIndex < 0) {
            beginIndex = 0;
        }
        endIndex = beginIndex + pageSize;
        if (endIndex > totalRow) {
            endIndex = totalRow;
        }
    }

    public int getPageNo() {
        return pageNo;
    }

    public int getTotalPage() {
        return totalPage;
    }

    public int getTotalRow() {
        return totalRow;
    }

    public int getPageSize() {
        return pageSize;
    }

    public int getBeginIndex() {
        return beginIndex;
    }

    public int getEndIndex() {
        return endIndex;
    }

    public List<T> getResultList() {
        return resultList;
    }

    public void setResultList(List<T> resultList) {
        this.resultList = resultList;
    }

}